import React from 'react'
import Component, { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import { Table, message, Radio, Button, Modal, Space } from 'antd'
import { addWindow } from '@redux/actions'
import style from '../../filingCaseManage/CaseManage.module.less'
import { confirmAction, formatDate, limitStr, strToNum } from '@js/tool'
import EditModal from './components/EditModal'
import AdminEditModal from './components/AdminEditModal'
import DetailModal from './components/DetailModal'
import { DownloadOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import { json2Excel } from '@src/assets/js/excel'
// const { Option } = Select

const { confirm } = Modal

// 获取表格字段配置
function getColumns () {
  const { userInfo } = this.props
  const isAdmin = userInfo.role_default === 'sysadmin'
  const list = [
    {
      title: '序号',
      dataIndex: 'key',
      key: 'index',
      align: 'center',
      width: 60
    },
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title'
    },
    {
      title: '问题类型',
      dataIndex: 'type',
      key: 'type',
      width: '100px'
    },
    {
      title: '问题描述',
      dataIndex: 'content',
      key: 'content',
      render: v => {
        return limitStr(v)
      }
    },
    {
      title: '创建时间',
      dataIndex: 'create_datetime',
      key: 'create_datetime',
      width: '110px',
      render: v => {
        v = strToNum(v)
        if (v) {
          return formatDate(v)
        }
      }
    },
    {
      title: '创建人',
      dataIndex: 'operator',
      key: 'operator',
      width: '80px'
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: '80px'
    },
    {
      title: '处理时间',
      dataIndex: 'complete_datetime',
      key: 'complete_datetime',
      width: '110px',
      render: (v) => {
        v = strToNum(v)
        if (v) {
          return formatDate(v)
        }
      }
    },
    {
      title: '处理结果',
      dataIndex: 'remark',
      key: 'remark',
      render: v => {
        return limitStr(v)
      }
    },
    {
      title: '操作',
      dataIndex: 'index',
      key: 'operate',
      width: 200,
      render: (value, line) => {
        return (
          <span className={style['operate-cell']}>
            {line.status === '提交' && !isAdmin && <span onClick={() => { this.setState({ visible: true, modifyData: line }) }}>编辑</span>}
            {isAdmin && <span onClick={() => { this.setState({ adminVisible: true, modifyData: line }) }}>编辑</span>}
            <span onClick={() => { this.setState({ detailVisible: true, modifyData: line }) }}>详情</span>
            {line.status === '提交' && <span onClick={() => this.delConfirm(line.id)}>删除</span>}
          </span>
        )
      }
    }
  ]
  return list
}

class SystemLog extends Component {
  state = {
    searchToggleBtn: false,
    loading: false,
    list: [],
    status: '全部',
    orderField: '',
    order: '',
    condition: [],
    pagination: {
      current: 1,
      pageSize: 20,
      total: 0,
      showSizeChanger: true,
      showQuickJumper: true,
      showTotal: total => `共 ${total} 条记录`,
      size: 'small'
    },
    visible: false,
    adminVisible: false,
    detailVisible: false,
    modifyData: null
  }

  formRef = React.createRef()

  // 改变状态
  changeStatus (status) {
    this.setState({
      status,
      pagination: {
        ...this.state.pagination,
        current: 1
      }
    }, () => {
      this.getTableData()
    })
  }

  // 获取数据
  getTableData () {
    const { pagination, status } = this.state
    const { current, pageSize } = pagination
    const condition = []
    if (status === '已解决') {
      condition.push({ k: 'status', o: 'in', v: '完成,暂不处理' })
    } else if (status === '未解决') {
      condition.push({ k: 'status', o: 'not in', v: '完成,暂不处理' })
    }
    this.setState({ condition })
    const data = {
      current,
      page_size: pageSize,
      condition: JSON.stringify(condition)
    }
    this.setState({ loading: true })
    this.$get('/api/common/maintainlog', data).then(res => {
      this.setState({ loading: false })
      if (res.status === 1) {
        this.setState({
          list: res.data.list.map((li, i) => {
            li.key = pageSize * (current - 1) + i + 1
            return li
          }),
          pagination: {
            ...pagination,
            total: res.data.total
          }
        })
      } else {
        return message.warning(res.message)
      }
    }).catch(() => this.setState({ loading: false }))
  }

  // 表格请求变化
  tableChange ({ current, pageSize }, filters, sorter) {
    this.setState({
      orderField: sorter.field,
      order: sorter.order,
      pagination: {
        ...this.state.pagination,
        current,
        pageSize
      }
    }, () => {
      this.getTableData()
    })
  }

  // 重置表格
  resetHandle () {
    this.setState({
      pagination: {
        ...this.state.pagination,
        current: 1
      }
    }, () => {
      this.getTableData()
    })
  }

  initFormByMeta () {
    const { status } = this.props.meta || {}
    if (status) {
      this.setState({
        status
      }, () => {
        this.getTableData()
      })
    } else {
      this.getTableData()
    }
  }

  delConfirm (id) {
    confirm({
      title: '提示',
      icon: <ExclamationCircleOutlined />,
      content: '您确定要删除吗？',
      onOk: () => {
        this.delHandle(id)
      },
      okText: '确定',
      cancelText: '取消'
    })
  }

  delHandle (id) {
    const hide = message.loading('删除中', 60)
    this.$delete(`/api/common/maintainlog/${id}`).then(res => {
      hide()
      if (res.status === 1) {
        this.getTableData()
      } else {
        return message.warning(res.message)
      }
    }).catch(() => hide())
  }

  // 获取当前查询条件的全部数据，并下载excel
  downloadExcel () {
    const current = 1
    const pageSize = 1000000
    const hide = message.loading('导出中', 300)
    this.$get('/api/common/maintainlog', {
      current,
      page_size: pageSize,
      condition: JSON.stringify(this.state.condition)
    }).then(res => {
      hide()
      if (res.status === 1) {
        const list = res.data.list.map((l, i) => {
          return {
            序号: pageSize * (current - 1) + i + 1,
            标题: l.title,
            问题类型: l.type,
            问题描述: l.content,
            创建时间: formatDate(l.create_datetime),
            创建人: l.operator,
            状态: l.status,
            处理时间: formatDate(l.complete_datetime),
            处理结果: l.remark
          }
        })
        json2Excel([{ data: list, sheetname: '系统问题反馈' }], '系统问题反馈')
      } else {
        return message.warning(res.message)
      }
    }).catch(() => hide())
  }

  componentDidUpdate (prev) {
    if (prev.meta !== this.props.meta) {
      this.initFormByMeta()
    }
  }

  componentDidMount () {
    this.initFormByMeta()
  }

  render () {
    const columns = getColumns.call(this)
    return (
      <div className={style.container}>
        <EditModal visible={this.state.visible} data={this.state.modifyData} hide={() => this.setState({ visible: false, modifyData: null })} refreshFn={() => this.getTableData()} />
        <AdminEditModal visible={this.state.adminVisible} data={this.state.modifyData} hide={() => this.setState({ adminVisible: false, modifyData: null })} refreshFn={() => this.getTableData()} />
        <DetailModal visible={this.state.detailVisible} data={this.state.modifyData} hide={() => this.setState({ detailVisible: false, modifyData: null })} />
        <div className={style['title-line']} style={{ marginBottom: '24px' }}>
          <span>{this.props.title}</span>
        </div>
        <div className={style['table-btns-line']}>
          <Space>
            <Button type='primary' ghost onClick={() => { this.setState({ visible: true, data: null }) }}>新增问题</Button>
            <Button onClick={() => confirmAction('您确定要导出excel吗？', () => this.downloadExcel())} icon={<DownloadOutlined />}>导出excel</Button>
          </Space>
          <div className={style['table-tabs-container']}>
            <Radio.Group value={this.state.status} onChange={v => this.changeStatus(v.target.value)}>
              <Radio.Button value='全部'>全部</Radio.Button>
              <Radio.Button value='已解决'>已解决</Radio.Button>
              <Radio.Button value='未解决'>未解决</Radio.Button>
            </Radio.Group>
          </div>
        </div>
        <div className={style['table-container']}>
          <Table loading={this.state.loading} columns={columns} dataSource={this.state.list} pagination={this.state.pagination} onChange={(...args) => this.tableChange(...args)} />
        </div>
      </div>
    )
  }
}

const mapState = mapStateToProps(function (state) {
  return {
    userInfo: state.basic.userInfo
  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {
    addWindow: (i) => dispatch(addWindow(i))
  }
})

export default connect(mapState, mapDispatch)(SystemLog)
